import 'dart:convert';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/index_nav/even/index_refresh_even.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bean/bind_terminal_info_confirm_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bean/binding_terminal_type.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/event/terminal_info_update_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/event/terminal_number_update_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/common_terminal_settings_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/event/terminal_auto_on_off_refresh_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/event/terminal_list_refresh_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/event/terminal_volume_refresh_event.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_index_event.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_stream_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'bean/bind_terminal_info_confirm_response_bean.dart';
import 'bean/binding_terminal_edit_upload_bean.dart';
import 'bean/binding_terminal_response_bean.dart';
import 'bean/terminal_detail_location_info.dart';
import 'event/play_file_update_event.dart';

class BindingTerminalViewModel extends BaseViewModel {
  ///app终端详情
  static const String TERMINAL_BIND_INFO_API =
     ServerApi.BASE_URL + "app/appTerminalBindInfo";

  ///app终端管理保存或绑定
  static const String TERMINAL_BIND_OR_SAVE_INFO_API =
     ServerApi.BASE_URL + "app/appTerminalSaveOrBind";

  ///app终端信息确认
  static const String TERMINAL_BIND_CONFIRM_INFO_API =
     ServerApi.BASE_URL + "app/appBindTerminalInfoConfirm";

  ///app终端管理保存绑定信息
  static const String TERMINAL_SAVE_INFO_API =
     ServerApi.BASE_URL + "app/appSaveTerminalInfo";

  ///app矫正终端摄像头
  static const String TERMINAL_FIX_CAMERA =
     ServerApi.BASE_URL + "app/appCorrectCamera";

  ///app即将开始矫正终端摄像头
  static const String TERMINAL_BEGIN_FIX_CAMERA =
     ServerApi.BASE_URL + "app/appBeginCorrectCamera";

  ///app正在绑定终端
  static const String BEGIN_BIND_TERMINAL =
     ServerApi.BASE_URL + "app/appBeginBind";

  ///app放弃调整终端
  static const String EXIT_BIND_TERMINAL =
     ServerApi.BASE_URL + "app/appExitBinding";

  ///根据gps获取位置信息
  static const String GET_DETAIL_INFO_BY_GPS = "https://apis.map.qq.com/ws/geocoder/v1?key=OKVBZ-THB3U-FDXVD-2Q5SD-AMMOH-EPB7D&language=cn";

  ///app解绑终端
  static const String UN_BIND_TERMINAL =
     ServerApi.BASE_URL + "app/appUnbindTer";

  ///app终端开关人脸识别  00启用 01关闭
  static const String CHANGE_FACE_RECOGNIZE_API =
     ServerApi.BASE_URL + "app/appChangeFaceRecognition";

  ///app终端开关音量  00开 01关
  static const String CHANGE_VOLUME_API =
     ServerApi.BASE_URL + "app/appSoundSwitch";

  ///app海报推送开关  pushflg 00开 01关
  static const String CHANGE_AI_POSTER_API =
     ServerApi.BASE_URL + "app/appUpdatePushflg";
  ///终端退出登录
  static const String TERMINAL_LOGIN_OUT =
     ServerApi.BASE_URL + "app/terLoginOut";
  ///终端设置开关机
  static const String TERMINAL_AUTO_ON_OFF =
     ServerApi.BASE_URL + "app/editHsnAutoSwitch";


  ValueNotifier<BindingTerminalDataBean> infoValueNotifier;
  ValueNotifier<PlaceHolderStatusType> statusTypeValueNotifier;
  ValueNotifier<BindTerminalInfoConfirmBean> confirmInfoValueNotifier;
  ValueNotifier<TerminalDetailLocationInfo> gpsInfoValueNotifier;

  VgStreamController saveController;

  BindingTerminalViewModel(BaseState<StatefulWidget> state) : super(state) {
    infoValueNotifier = ValueNotifier(null);
    confirmInfoValueNotifier = ValueNotifier(null);
    statusTypeValueNotifier = ValueNotifier(PlaceHolderStatusType.loading);
    gpsInfoValueNotifier = ValueNotifier(null);
    saveController = newAutoReleaseBroadcast();
  }

  @override
  void onDisposed() {
    infoValueNotifier?.dispose();
    confirmInfoValueNotifier?.dispose();
    statusTypeValueNotifier?.dispose();
    gpsInfoValueNotifier?.dispose();
    super.onDisposed();
  }

  ///获取顶部信息请求
  void getBindingTerminalInfo(String hsnId) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    VgHttpUtils.get(TERMINAL_BIND_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "companyid": UserRepository.getInstance().companyId ?? "",
          "hsn": hsnId ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          BindingTerminalResponseBean bean =
          BindingTerminalResponseBean.fromMap(val);
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            infoValueNotifier?.value = bean?.data;
          }
          loading(false);
        }, onError: (msg) {
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }));
  }


  ///获取顶部信息请求
  void getTerminalDetailInfoWithCache(String hsnId) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    String cacheKey = TERMINAL_BIND_INFO_API
        + (UserRepository.getInstance().companyId??"") + hsnId;
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        print("获取缓存终端详情：" + cacheKey + "   " + jsonStr);
        Map map = json.decode(jsonStr);
        BindingTerminalResponseBean bean = BindingTerminalResponseBean.fromMap(map);
        if(bean != null){
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            infoValueNotifier?.value = bean?.data;
          }
          loading(false);
        }
        getTerminalDetailInfo(hsnId);
      }else{
        getTerminalDetailInfo(hsnId);
      }
    });
  }

  ///获取顶部信息请求
  void getTerminalDetailInfo(String hsnId) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    String cacheKey = TERMINAL_BIND_INFO_API
        + (UserRepository.getInstance().companyId??"") + hsnId;
    VgHttpUtils.get(TERMINAL_BIND_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "companyid": UserRepository.getInstance().companyId ?? "",
          "hsn": hsnId ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          BindingTerminalResponseBean bean =
          BindingTerminalResponseBean.fromMap(val);
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            infoValueNotifier?.value = bean?.data;
          }
          if(bean!=null){
            SharePreferenceUtil.putString(cacheKey, json.encode(bean));
            print("缓存文件详情：" + cacheKey + "   " + json.encode(bean));
          }
          loading(false);
        }, onError: (msg) {
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }));
  }

  ///保存或绑定
  void saveTerminalOrBind(
      BuildContext context, BindingTermialEditUploadBean uploadBean) async {
    if (uploadBean == null) {
      return;
    }
    if(StringUtils.isEmpty(uploadBean?.terminal_picurl)){
      _toSaveHttp(context, uploadBean);
      return;
    }
    VgMatisseUploadUtils.uploadSingleImage(
        uploadBean?.terminal_picurl,
        VgBaseCallback(onSuccess: (String netPic) {
          if (StringUtils.isNotEmpty(netPic)) {
            uploadBean.terminal_picurl = netPic;
            _toSaveHttp(context, uploadBean);
          } else {
            VgToastUtils.toast(context, "图片上传失败");
          }
        }, onError: (String msg) {
          VgToastUtils.toast(context, msg);
        }));
  }

  void _toSaveHttp(
      BuildContext context, BindingTermialEditUploadBean uploadBean) {
    VgHudUtils.show(context, "保存中");
    VgHttpUtils.get(TERMINAL_BIND_OR_SAVE_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "companyid": UserRepository.getInstance().companyId ?? "",
          "adress": uploadBean?.address ?? "",
          "auto_onoff":uploadBean?.autoOffStatusType?.getParamsValue() ?? "",
          "auto_onoff_time": uploadBean?.getAutoOffTimeStr() ?? "",
          "backup": uploadBean?.backup ?? "",
          "close_camera": uploadBean?.cameraStatusType?.getParamsValue() ?? "",
          "gps": uploadBean?.gps ?? "",
          "hsn": uploadBean?.hsn ?? "",
          "is_bind": uploadBean?.is_bind ?? "",
          "mid": uploadBean?.mid ?? "",
          "rcaid": uploadBean?.rcaid ?? 0,
          "terminal_name": uploadBean?.terminal_name ?? "",
          "terminal_picurl": uploadBean?.terminal_picurl ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          RouterUtils.pop(context,result: true);
          VgToastUtils.toast(AppMain.context, "保存成功");
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }


  ///获取绑定终端信息详情
  void getBindingTerminalConfirmInfo(BuildContext context, String hsnId) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    loading(true, msg: "信息获取中");
    VgHttpUtils.get(TERMINAL_BIND_CONFIRM_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "hsn": hsnId ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          loading(false);
          BindTerminalInfoConfirmResponseBean bean =
          BindTerminalInfoConfirmResponseBean.fromMap(val);
          statusTypeValueNotifier?.value = null;
          confirmInfoValueNotifier?.value = bean?.data;
        }, onError: (msg) {
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }));
  }


  ///新绑定接口
  void saveTerminalInfo(
      BuildContext context, BindingTermialEditUploadBean uploadBean, {VoidCallback callback, String router}) async {
    if (uploadBean == null) {
      return;
    }
    if(StringUtils.isEmpty(uploadBean?.terminal_picurl)){
      _toSaveTerminalInfo(context, uploadBean, callback: callback, router: router);
      return;
    }
    VgMatisseUploadUtils.uploadSingleImage(
        uploadBean?.terminal_picurl,
        VgBaseCallback(onSuccess: (String netPic) {
          if (StringUtils.isNotEmpty(netPic)) {
            uploadBean.terminal_picurl = netPic;
            _toSaveTerminalInfo(context, uploadBean, callback: callback, router: router);
          } else {
            VgToastUtils.toast(context, "图片上传失败");
          }
        }, onError: (String msg) {
          VgToastUtils.toast(context, msg);
        }));
  }



  void _toSaveTerminalInfo(
      BuildContext context, BindingTermialEditUploadBean uploadBean, {VoidCallback callback, String router}) {
    VgHudUtils.show(context, "保存中");
    VgHttpUtils.get(TERMINAL_SAVE_INFO_API,
        params: uploadBean?.cameraStatusType?.getParamsValue() == null?
        {
          "mid": uploadBean?.mid ?? "",
          "flg": uploadBean?.flg??"",
          "caid": uploadBean?.caid??"",
          "screen_direction": uploadBean?.screenOrientationType?.getParamsValue()??"",
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": uploadBean?.rcaid ?? 0,
          "hsn": uploadBean?.hsn ?? "",
          "position": uploadBean?.position ?? "",
          "enable_face_recognition": uploadBean?.faceRecognitionType?.getParamsValue() ?? "",
          "screen_specs": uploadBean?.screenSizeType?.getParamsValue() ?? "",
          "auto_onoff":uploadBean?.autoOffStatusType?.getParamsValue() ?? "",
          "cameratype": uploadBean?.cameratype ?? "00",
          "correct_camera": uploadBean?.correctCamera ?? 0,
          "auto_onoff_time": uploadBean?.getAutoOffTimeStr() ?? "",
          "start_camera_distance": uploadBean?.cameraStartDistance ?? "",
          "terminal_name": uploadBean?.terminal_name ?? "",
          "terminal_picurl": uploadBean?.terminal_picurl ?? "",
          "time_interval": uploadBean?.punchInInterval ?? "",
          "type": uploadBean?.deviceType?.getParamsValue() ?? "",
          "frame": uploadBean?.faceSize ?? "2",
          "screen_touch": uploadBean?.screenTouch ?? "00",
        }
            :{
          "mid": uploadBean?.mid ?? "",
          "flg": uploadBean?.flg??"",
          "caid": uploadBean?.caid??"",
          "screen_direction": uploadBean?.screenOrientationType?.getParamsValue()??"",
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": uploadBean?.rcaid ?? 0,
          "hsn": uploadBean?.hsn ?? "",
          "position": uploadBean?.position ?? "",
          "close_camera": uploadBean?.cameraStatusType?.getParamsValue() ?? null,
          "enable_face_recognition": uploadBean?.faceRecognitionType?.getParamsValue() ?? "",
          "screen_specs": uploadBean?.screenSizeType?.getParamsValue() ?? "",
          "auto_onoff":uploadBean?.autoOffStatusType?.getParamsValue() ?? "",
          "cameratype": uploadBean?.cameratype ?? "00",
          "correct_camera": uploadBean?.correctCamera ?? 0,
          "auto_onoff_time": uploadBean?.getAutoOffTimeStr() ?? "",
          "start_camera_distance": uploadBean?.cameraStartDistance ?? "",
          "terminal_name": uploadBean?.terminal_name ?? "",
          "terminal_picurl": uploadBean?.terminal_picurl ?? "",
          "time_interval": uploadBean?.punchInInterval ?? "",
          "type": uploadBean?.deviceType?.getParamsValue() ?? "",
          "frame": uploadBean?.faceSize ?? "2",
          "screen_touch": uploadBean?.screenTouch ?? "00",
        },
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          saveController.add(null);
          VgToastUtils.toast(AppMain.context, "保存成功");
          VgEventBus.global.send(new TerminalListRefreshEvent());
          if(callback != null){
            callback();
          }
          if(StringUtils.isNotEmpty(router)){
            RouterUtils.popUntil(context, router, rootNavigator: false);
          }else{
            RouterUtils.popUntil(context, AppMain.ROUTER,
                rootNavigator: false);
          }
        }, onError: (msg) {
          VgHudUtils.hide(context);
          if("请检测对应终端是否在线。" == msg){
            saveController.add(null);
            VgToastUtils.toast(AppMain.context, "保存成功");
          }else{
            VgToastUtils.toast(AppMain.context, msg);
          }
        }));
  }

  ///调整app控制终端
  void fixCamera(String mid, int rcaid, String hsnId, String flg, int angle, String type) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    VgHttpUtils.get(TERMINAL_FIX_CAMERA,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": rcaid,
          "hsn": hsnId ?? "",
          "flg": flg,
          "angle": angle ?? "",
          "type": type ?? "00",
        },
        callback: BaseCallback(onSuccess: (val) {
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          VgToastUtils.toast(AppMain.context, "请观测显示屏端图像是否正确");
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }));
  }

  ///通知终端 即将进行调整
  void notifyTerminal(String hsnId) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    VgHttpUtils.get(TERMINAL_BEGIN_FIX_CAMERA,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "hsn": hsnId ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          VgToastUtils.toast(AppMain.context, "连接终端成功");
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }));
  }

  ///app正在绑定终端
  void beginBindTerminal(String hsnId) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    VgHttpUtils.get(BEGIN_BIND_TERMINAL,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "hsn": hsnId ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }));
  }

  ///app正在绑定终端
  void exitBindTerminal(String hsnId) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    VgHttpUtils.get(EXIT_BIND_TERMINAL,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "hsn": hsnId ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }));
  }

  ///设置摄像头信息
  void setCameraSettings(BuildContext context, String mid, int rcaid, String hsnId, String flg, int angle, String type) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    VgHudUtils.show(context, "保存中");
    VgHttpUtils.get(TERMINAL_SAVE_INFO_API,
        params: {
          "mid": mid??"",
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": rcaid,
          "hsn": hsnId ?? "",
          "flg": flg,
          "correct_camera": angle ?? "",
          "cameratype": type ?? "00",
        },
        callback: BaseCallback(onSuccess: (val) {
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          VgHudUtils.hide(context);
          RouterUtils.pop(context,result: false);
          VgToastUtils.toast(AppMain.context, "保存成功");

        }, onError: (msg) {
          if("请检测对应终端是否在线。" !=  msg){
            VgToastUtils.toast(AppMain.context, msg);
            statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
          }else{
            VgHudUtils.hide(context);
            RouterUtils.pop(context,result: false);
            VgToastUtils.toast(AppMain.context, "保存成功");
          }

        }));
  }

  ///调整刷脸记录间隔
  void setFaceSize(String mid, int rcaid, String hsnId, String flg, int frame){
    VgHttpUtils.get(TERMINAL_SAVE_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": rcaid,
          "hsn": hsnId ?? "",
          "flg": flg,
          "frame": frame ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          VgToastUtils.toast(AppMain.context, "保存成功");
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }));
  }


  ///调整摄像头启动距离
  void setCameraStartDistance(String mid, int rcaid, String hsnId, String flg, double cameraStart){
    VgHttpUtils.get(TERMINAL_SAVE_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": rcaid,
          "hsn": hsnId ?? "",
          "flg": flg,
          "start_camera_distance": cameraStart ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          VgToastUtils.toast(AppMain.context, "保存成功");
        }, onError: (msg) {
          if("请检测对应终端是否在线。" !=  msg){
            VgToastUtils.toast(AppMain.context, msg);
            statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
          }else{
            VgToastUtils.toast(AppMain.context, "保存成功");
          }
        }));
  }

  ///调整刷脸记录间隔
  void setPunchInInterval(String mid, int rcaid, String hsnId, String flg, int interval){
    VgHttpUtils.get(TERMINAL_SAVE_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": rcaid,
          "hsn": hsnId ?? "",
          "flg": flg,
          "time_interval": interval ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          VgToastUtils.toast(AppMain.context, "保存成功");
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }));
  }

  ///调整自动开关机时间
  void setAutoOnOffTime(int rcaid, String hsnId, String flg, String time, String status, String repeatWeek, {bool needPop}){
    VgHttpUtils.get(TERMINAL_SAVE_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": rcaid,
          "hsn": hsnId ?? "",
          "flg": flg,
          "auto_onoff_time": time ?? "",
          "auto_onoff": status ?? "",
          "auto_onoff_week": repeatWeek ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          VgEventBus.global.send(new TerminalAutoOnOffRefreshEvent());
          VgToastUtils.toast(AppMain.context, "保存成功");
          if(needPop??false){
            RouterUtils.pop(AppMain.context);
          }
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }));
  }

  ///保存终端自动开关机
  void saveAutoOnOffByWeek(BuildContext context, String hsn,
      int rcaid, ComAutoSwitchBean comAutoSwitch, {bool needPop, VoidCallback callback, bool noToast}){
    //autoOnoff 00未设置 01已设置
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(TERMINAL_AUTO_ON_OFF,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
      "acid": rcaid ?? "",
      "rcaid": rcaid ?? "",
      "companyid": UserRepository.getInstance().companyId ?? "",

      "autoOnoff": comAutoSwitch?.autoOnoff ?? "00",

      "autoMon": comAutoSwitch?.autoMon ?? "00",
      "autoTues": comAutoSwitch?.autoTues ?? "00",
      "autoWed": comAutoSwitch?.autoWed ?? "00",
      "autoThur": comAutoSwitch?.autoThur ?? "00",
      "autoFri": comAutoSwitch?.autoFri ?? "00",
      "autoSat": comAutoSwitch?.autoSat ?? "00",
      "autoSun": comAutoSwitch?.autoSun ?? "00",

      "monTime": comAutoSwitch?.monTime ?? "",
      "tuesTime": comAutoSwitch?.tuesTime ?? "",
      "wedTime": comAutoSwitch?.wedTime ?? "",
      "thurTime": comAutoSwitch?.thurTime ?? "",
      "friTime": comAutoSwitch?.friTime ?? "",
      "satTime": comAutoSwitch?.satTime ?? "",
      "sunTime": comAutoSwitch?.sunTime ?? "",
      "restflg": comAutoSwitch?.restflg ?? "01",

    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgEventBus.global.send(new TerminalAutoOnOffRefreshEvent());
          if(!(noToast??false)){
            VgToastUtils.toast(AppMain.context, "保存成功");
          }
          if(callback != null){
            callback.call();
          }
          if(needPop??false){
            RouterUtils.pop(AppMain.context);
          }
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///编辑基本信息
  void setBasicInfo(BuildContext context, BindingTermialEditUploadBean uploadBean, {bool needStay})async {
    VgHudUtils.show(context, "保存中");
    VgHttpUtils.get(TERMINAL_SAVE_INFO_API,
        params: {
          "mid": uploadBean?.mid??"",
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": uploadBean?.rcaid ?? 0,
          "caid": uploadBean?.caid??"",
          "hsn": uploadBean?.hsn ?? "",
          "flg": "01",
          "terminal_name": uploadBean?.terminal_name ?? "",
          "position": uploadBean?.position ?? "",
          "screen_specs": uploadBean?.screenSizeType?.getParamsValue() ?? "",
          "screen_direction": uploadBean?.screenOrientationType?.getParamsValue() ?? "",
          "type": uploadBean?.deviceType?.getParamsValue() ?? "",
          "enable_face_recognition": uploadBean?.faceRecognitionType?.getParamsValue() ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          if(!(needStay??false)){
            RouterUtils.pop(context,result: true);
          }
          VgEventBus.global.send(new TerminalListRefreshEvent());
          VgEventBus.global.send(new PlayFileUpdateEvent("终端有更新"));
          VgToastUtils.toast(AppMain.context, "保存成功");
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///更新终端照片
  void setTerminalPic(BuildContext context, int rcaid, String hsnId, String flg, String picurl){
    VgMatisseUploadUtils.uploadSingleImage(
        picurl,
        VgBaseCallback(onSuccess: (String netPic) {
          if (StringUtils.isNotEmpty(netPic)) {
            VgHttpUtils.get(TERMINAL_SAVE_INFO_API,
                params: {
                  "authId": UserRepository.getInstance().authId ?? "",
                  "rcaid": rcaid,
                  "hsn": hsnId ?? "",
                  "flg": flg,
                  "terminal_picurl": netPic ?? "",
                },
                callback: BaseCallback(onSuccess: (val) {
                  VgEventBus.global.send(new PlayFileUpdateEvent("终端照片更新"));
                }, onError: (msg) {
                  VgToastUtils.toast(AppMain.context, msg);
                }));
          } else {
            VgToastUtils.toast(context, "图片上传失败");
          }
        }, onError: (String msg) {
          VgToastUtils.toast(context, msg);
        }));
  }

  ///更新终端照片
  void setTerminalPosition(BuildContext context, int rcaid, String hsnId, String flg, String position){
    VgHttpUtils.get(TERMINAL_SAVE_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": rcaid,
          "hsn": hsnId ?? "",
          "flg": flg,
          "position": position ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          VgEventBus.global.send(new TerminalInfoUpdateEvent("终端摆放位置更新"));
          VgEventBus.global.send(RefreshBranchDetailEvent());
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///修改备注说明
  void setBackup(int rcaid, String hsnId, String flg, String terminalName){
    VgHttpUtils.get(TERMINAL_SAVE_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": rcaid,
          "hsn": hsnId ?? "",
          "flg": flg,
          "terminal_name": terminalName ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          VgToastUtils.toast(AppMain.context, "保存成功");
          VgEventBus.global.send(new TerminalInfoUpdateEvent("终端备注说明更新"));
          VgEventBus.global.send(RefreshBranchDetailEvent());
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///修改备注说明
  void setCbid(int rcaid, String hsnId, String flg, String cbid){
    VgHttpUtils.get(TERMINAL_SAVE_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "rcaid": rcaid,
          "hsn": hsnId ?? "",
          "flg": flg,
          "cbid": cbid ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          VgEventBus.global.send(new TerminalInfoUpdateEvent("终端cbid更新"));
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///根据gps获取位置信息
  void getDetailInfoByGps(BuildContext context, String gps) {
    if (StringUtils.isEmpty(gps)) {
      return;
    }
    Map<String,dynamic> map = {
      "location": gps,
    };
    HttpUtils.get(url: GET_DETAIL_INFO_BY_GPS, query: map).then((resp){
      TerminalDetailLocationInfo bean =
      TerminalDetailLocationInfo.fromMap(resp?.data);
      if(bean == null || bean.status!= 0){
        return;
      }
      gpsInfoValueNotifier?.value = bean;
    });
  }

  void unBindTerminal(
      BuildContext context, String hsn, {int terminalCount, String router, VoidCallback callback}) {
    if (StringUtils.isEmpty(hsn)) {
      return;
    }
    VgHudUtils.show(context, "操作中");
    VgHttpUtils.get(UN_BIND_TERMINAL,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "hsn": hsn,
        },
        callback: BaseCallback(onSuccess: (val) {
          if(!isStateDisposed){
            VgEventBus.global.send(TerminalNumberUpdateEvent('终端有删减', hsn: hsn));
          }
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgHudUtils.hide(context);
          if(callback != null){
            callback.call();
          }else{
            //终端数量只有一个的话，直接退回首页
            if(terminalCount != null && terminalCount <= 1){
              RouterUtils.popUntil(context, AppMain.ROUTER,
                  rootNavigator: false);
            }else{
              if(StringUtils.isNotEmpty(router)){
                RouterUtils.popUntil(context, router, rootNavigator: false);
              }else{
                RouterUtils.pop(context,result: true);
              }
            }
          }
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///开关人脸识别
  void changeFace(BuildContext context, String hsnId, String type) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(CHANGE_FACE_RECOGNIZE_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "hsn": hsnId ?? "",
          "type": type ?? "00",
        },
        callback: BaseCallback(onSuccess: (val) {
          getTerminalDetailInfo(hsnId);
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          VgToastUtils.toast(AppMain.context, "操作成功");
          VgHudUtils.hide(context);
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///开关声音
  ///onOff 00开 01关
  void changeVolume(BuildContext context, String hsnId, String onOff, int volume, {bool needPop}) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(CHANGE_VOLUME_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "hsn": hsnId ?? "",
          "onOff": onOff ?? "00",
          "volume": volume ?? 50,
        },
        callback: BaseCallback(onSuccess: (val) {
          getTerminalDetailInfo(hsnId);
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          VgToastUtils.toast(AppMain.context, "操作成功");
          if(needPop??false){
            RouterUtils.pop(context, result: volume);
          }
          VgEventBus.global.send(new TerminalVolumeRefreshEvent(blockUpdate: false));
            // //通知首页更新
            // VgEventBus.global.send(IndexRefreshEven(hsn: hsnId));
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///开关海报
  ///pushflg 00开 01关
  void changeAiPoster(BuildContext context, String hsnId, String pushflg) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(CHANGE_AI_POSTER_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "hsn": hsnId ?? "",
          "pushflg": pushflg ?? "00",
        },
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          getTerminalDetailInfo(hsnId);
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          VgToastUtils.toast(AppMain.context, "操作成功");
          //
          VgEventBus.global.send(IndexRefreshEven(hsn: hsnId));
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///终端退出登录
  ///00开启 01关闭
  void terminalLoginOut(BuildContext context, String hsnId, String power) {
    if (StringUtils.isEmpty(hsnId)) {
      return;
    }
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(TERMINAL_LOGIN_OUT,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "hsn": hsnId ?? "",
          "power": power ?? "01",
        },
        callback: BaseCallback(onSuccess: (val) {
          getTerminalDetailInfo(hsnId);
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          VgToastUtils.toast(AppMain.context, "操作成功");
          VgEventBus.global.send(TerminalListRefreshEvent());
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

}
